package com.bianguo.android.ioclibrary.handlers;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;

public class ListenerInvocationHandler implements InvocationHandler {

    private Object target;
    private HashMap<Object, Method> methodMap;
    private final static long QUICK_EVENT_TIME_SPAN = 200; // 阻塞事件
    private long lastClickTime;

    public ListenerInvocationHandler(Object target) {
        this.target = target;
        methodMap = new HashMap<>();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (target != null) {
            long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - lastClickTime > QUICK_EVENT_TIME_SPAN) {
                lastClickTime = currentTimeMillis;
                method = methodMap.get(method.getName());
                if (method != null) {
                    return method.invoke(target, args);
                }
            }
        }
        return null;
    }

    public void addMethod(String methodName, Method method) {
        methodMap.put(methodName, method);
    }
}
